import * as passport from "passport";
import {ExtractJwt, Strategy as JwtStrategy} from "passport-jwt";
import {PlayerModel} from "../database/models/player";


export function initJWTPassport(jwtSecret: string) {

  passport.use(new JwtStrategy({
      secretOrKey: jwtSecret,
      jwtFromRequest: ExtractJwt.fromHeader('x-jwt'),
      ignoreExpiration: true,
    }, async function (jwt_payload, done) {
      const player = await PlayerModel.findById(jwt_payload._id)

      if (player) {
        if (player.cookie === jwt_payload.cookie) {
          done(null, player)
        } else {
          done(null, null, Error('AUTH_EXPIRED'))
        }
      } else {
        done(null, null, Error('NO_SUCH_USER'))
      }
    }
  ))

  passport.deserializeUser((user, done) => done(null, user))
  passport.serializeUser((user, done) => done(null, user))

  return passport
}

export const jwtAuthMiddleware = passport.authenticate('jwt', {failureRedirect: '/authfail'})
